package csu.web.mypetstore.web.servlet;

import com.alibaba.fastjson.JSON;
import csu.web.mypetstore.domain.*;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Iterator;

public class AddCartServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String itemId = "";

        itemId = req.getParameter("itemId");
        AddCart addCart = (AddCart) session.getAttribute("addCart");
        Cart cart = (Cart) session.getAttribute("cart");


        CatalogService catalogService = new CatalogService();

        Item item = catalogService.getItem(itemId);
        addCart.addItem(item, true);
        Iterator<CartItem> addCartItems = addCart.getAllCartItems();
        Iterator<CartItem> cartItems = cart.getAllCartItems();


        while (cartItems.hasNext()){
            CartItem cartItem = (CartItem) cartItems.next();
            try {
                String Id = cartItem.getItem().getItemId();

                if(Id.equals(itemId)){
                    while(addCartItems.hasNext()){
                        CartItem addCartItem = addCartItems.next();
                        try{
                            String id = addCartItem.getItem().getItemId();
                            if( id.equals(itemId) ){
                                addCartItem.setQuantity(cartItem.getQuantity());
                                break;
                            }
                        }catch (Exception e){}
                    }
                    break;
                }
            }catch (Exception e) {}
        }


        session.setAttribute("cart", cart);
        session.setAttribute("addCart", addCart);

        String result = JSON.toJSONString(addCart.getSubTotal());
        System.out.println(result);
        resp.setContentType("text/json");
        PrintWriter out = resp.getWriter();
        out.println(result);



    }
}
